<?php


namespace app\api\model;

use app\api\service\Bank;
use app\common\exception\BaseException;
use app\common\model\UserBcard as UserBcardModel;
use app\common\service\Order as OrderService;

class UserBcard extends UserBcardModel
{
    /**
     * 判断银行卡是否绑定过
     * @param $user_id  用户编号
     * @param $accno    银行卡号
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function check($user_id,$accno){
        $model = (new static());
        $filter = [
            'user_id' => $user_id,
            'accno' => $accno,
            'wxapp_id' => self::$wxapp_id,
        ];
        return  ($model->where($filter)->find())?false:true;
    }

    /**
     * 绑定银行卡与用户
     * @param $data
     * @return bool|mixed
     */
    public static function insertData($data){
        $model = (new static());
        $filter = [
            'user_id' => $data['user_id'],
            'orderno' => OrderService::createOrderNo(),
            'bankname' => $data['acctbankname'],
            'accno' => $data['acctid'],
            'status' => 1,
            'wxapp_id' => self::$wxapp_id,
        ];
        return $model->save($filter)?$model->bcard_id:false;
    }

    /**
     * 修改结算银行卡数据
     * @param array $data
     * @return bool
     * @throws BaseException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public  function changecard(array $data){
        $ubmodel = static::get($data['user_bcard_id']);
        if (!$ubmodel){
            $this->setError("很抱歉，找不到对应的银行卡数据");
        }
        //旧银行账户号
        $data['old_accno'] = $ubmodel['accno'];
        $this->startTrans();
        try {
            $bank = new Bank();
            if ($bank->changeBcard($data)){
                $new_data = [
                    'bankname' => $data['bankname'],
                    'accno' => $data['acctid']
                ];
                $ubmodel->save($new_data);
            }
            $this->commit();
        }catch (\Exception $e) {
            $this->rollback();
            throw new BaseException(['msg' => $e->getMessage()]);
        }
        return true;

    }

    /**
     * 获取用户对应绑定银行卡
     * @param $user_id
     */
    public function getcards($user_id){
        return $this->where(['user_id'=>$user_id])->find();
    }
}